
// const port = "http://192.168.22.40:8082"
const port = "http://192.168.23.46:8082/"



//初始获取轮播图
chrome.action.onClicked.addListener(function (tab) {

    chrome.tabs.query({ title: "网站信息抓取助手" }, async function (tabs) {
        let titleArr = [];
        for (let i = 0; i < tabs.length; i++) {
            titleArr.push(tabs[i].title)
        }


        if (titleArr.includes("网站信息抓取助手")) {
            chrome.tabs.update(tabs[0].id, { active: true });
        }
        else {

            //获取轮播图片
            await fetch("https://tpis.smartsousou.com/TPLinkRun/advertisingURL.js", { method: "GET" })
                .then(res => res.text())
                .then(res => {
                    let content = res.split("advertisingArr=")[1]
                    let regxUrl = /http.\S+"/g

                    let urlContent = content.match(regxUrl)
                    // console.log(urlContent)
                    let newUrl = []

                    urlContent.forEach(item => {
                        item = item.slice(0, item.length - 1)
                        newUrl.push(item)
                    })

                    chrome.storage.local.set({ 'slideshowUrl': newUrl })

                })



            chrome.tabs.create({
                url: chrome.runtime.getURL('html/index.html')
            });

        }
    });

});





// 接收 请求
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log(request.data)
        //登录请求
        if (request.data.type == "login") {
            console.log("进入login")

            let formData = new URLSearchParams();
            formData.append('LoginId', request.data.LoginId);
            formData.append('LoginPwd', request.data.LoginPwd);
            fetch(`${port}/api/SysAdmins/TopeasyWebsiteLogin`, { method: "post", body: formData })
                .then(response => response.json())
                .then(response => {
                    if (response.Result.Result) {
                        console.log(response.Result)
                        // 登录成功 
                        chrome.storage.local.set({ "TopeasyAccountCode": response.Result.AccountCode })
                            .then((res) => {
                                console.log(res, "登录后的accountcode")
                                sendResponse({ "status": 1 })
                            });
                    }
                })
                .catch(err => {
                    sendResponse({ "status": 0 })
                    console.log(err)
                })

        }


        //单个保存请求
        else if (request.data.type == "saveData") {

            console.log("进入saveDate")

            let body = request.data.data
            console.log(body)


            let urlencoded = new URLSearchParams();
            urlencoded.append("Id", "");
            urlencoded.append("AccountCode", body.AccountCode);
            urlencoded.append("Domain", body.Domain);
            urlencoded.append("Protocol", body.Protocol);
            urlencoded.append("Trip", "");
            urlencoded.append("DomainContactWareHouseList[0][Id]", "");
            urlencoded.append("DomainContactWareHouseList[0][DomainId]", "");
            urlencoded.append("DomainContactWareHouseList[0][ContactType]", body.DomainContactWareHouseList[0].ContactType);
            urlencoded.append("DomainContactWareHouseList[0][ContactValue]", body.DomainContactWareHouseList[0].ContactValue);
            urlencoded.append("DomainContactWareHouseList[0][SourceUrl]", body.DomainContactWareHouseList[0].SourceUrl);
            urlencoded.append("DomainContactWareHouseList[0][SourceType]", "0");
            urlencoded.append("DomainContactWareHouseList[0][Trip]", "");


            fetch(`${port}/api/Index/UpsertToDomain`, {
                method: "POST",
                headers: {
                    "Content-type": "application/x-www-form-urlencoded",
                    "mAccountCode": request.data.mAccountCode
                },
                body: urlencoded
            })
                .then(response => response.json())
                .then(res => {
                    sendResponse({ status: "1" })
                })
                .catch(err => {
                    sendResponse({ status: "0" })
                })
        }

        //保存所有数据  请求
        else if (request.data.type == "AllDataSave") {

            let body = request.data.data
            console.log(body, "进入AllDataSave")


            let urlencoded = new URLSearchParams();
            urlencoded.append("Id", "");
            urlencoded.append("AccountCode", request.data.mAccountCode);
            urlencoded.append("Domain", body.Domain);
            urlencoded.append("Protocol", body.Protocol);
            urlencoded.append("Trip", "");
            for (let i = 0; i < body.DomainContactWareHouseList.length; i++) {
                urlencoded.append("DomainContactWareHouseList[" + i + "][Id]", "");
                urlencoded.append("DomainContactWareHouseList[" + i + "][DomainId]", "");
                urlencoded.append("DomainContactWareHouseList[" + i + "][ContactType]", body.DomainContactWareHouseList[i].ContactType);
                urlencoded.append("DomainContactWareHouseList[" + i + "][ContactValue]", body.DomainContactWareHouseList[i].ContactValue);
                urlencoded.append("DomainContactWareHouseList[" + i + "][SourceUrl]", body.DomainContactWareHouseList[i].SourceUrl);
                urlencoded.append("DomainContactWareHouseList[" + i + "][SourceType]", "0");
                urlencoded.append("DomainContactWareHouseList[" + i + "][Trip]", "");
            }



            fetch(`${port}/api/Index/UpsertToDomain`, {
                method: "POST",
                headers: {
                    "Content-type": "application/x-www-form-urlencoded",
                    "mAccountCode": request.data.EncryptAccountCode
                },
                body: urlencoded
            })
                .then(response => response.json())
                .then(res => {
                    sendResponse({ status: "1" })
                })
                .catch(err => {
                    sendResponse({ status: "0" })
                    console.log(err)
                })

        }

        //添加域名请求
        else if (request.data.type == "AddDomain") {
            console.log("进入AddDomain")

            let body = request.data.data
            console.log(body, "body")

            let urlencoded = new URLSearchParams();
            urlencoded.append("Id", "");
            urlencoded.append("AccountCode", body.AccountCode);
            urlencoded.append("Domain", body.Domain);
            urlencoded.append("Protocol", body.Protocol);
            urlencoded.append("Trip", "");
            urlencoded.append("DomainContactWareHouseList[0][Id]", "");
            urlencoded.append("DomainContactWareHouseList[0][DomainId]", "");
            urlencoded.append("DomainContactWareHouseList[0][ContactType]", SelectTypeToNum(body.DomainContactWareHouseList[0].ContactType));
            urlencoded.append("DomainContactWareHouseList[0][ContactValue]", body.DomainContactWareHouseList[0].ContactValue);
            urlencoded.append("DomainContactWareHouseList[0][SourceUrl]", body.DomainContactWareHouseList[0].SourceUrl);
            urlencoded.append("DomainContactWareHouseList[0][SourceType]", "0");
            urlencoded.append("DomainContactWareHouseList[0][Trip]", "");

            fetch(`${port}/api/Index/UpsertToDomain`, {
                method: "POST",
                headers: {
                    "Content-type": "application/x-www-form-urlencoded",
                    "mAccountCode": request.data.mAccountCode
                },
                body: urlencoded
            })
                .then(response => response.json())
                .then(res => {
                    sendResponse({ status: "1" })
                })
                .catch(err => {
                    console.log(err)
                    sendResponse({ status: "0" })
                })

        }

        else if (request.data.type == "toView") {
            chrome.tabs.query({ title: "网站信息抓取助手" }, async function (tabs) {
                let titleArr = [];
                for (let i = 0; i < tabs.length; i++) {
                    titleArr.push(tabs[i].title)
                }


                if (titleArr.includes("网站信息抓取助手")) {
                    chrome.tabs.update(tabs[0].id, { active: true });
                }
                else {

                    //获取轮播图片
                    await fetch("https://tpis.smartsousou.com/TPLinkRun/advertisingURL.js", { method: "GET" })
                        .then(res => res.text())
                        .then(res => {
                            let content = res.split("advertisingArr=")[1]
                            let regxUrl = /http.\S+"/g

                            let urlContent = content.match(regxUrl)
                            // console.log(urlContent)
                            let newUrl = []

                            urlContent.forEach(item => {
                                item = item.slice(0, item.length - 1)
                                newUrl.push(item)
                            })

                            chrome.storage.local.set({ 'slideshowUrl': newUrl })

                        })



                    chrome.tabs.create({
                        url: chrome.runtime.getURL('html/index.html')
                    });

                }
            });
        }
        return true;

    });






//获取网站所有联系方式
chrome.contextMenus.create({
    id: "ALLContentMenu",
    contexts: ["page"],
    title: "获取网站所有联系方式",
});





//上下文
chrome.contextMenus.create({
    id: "AppendSelectnContentMneu",
    contexts: ["selection"],
    title: "添加到联系方式",
});


const childList = ["Email", "Facebook", "Twitter", "Skype", "YouTube", "Instagram", "Pinterest", "Tel", "Fax", "地址", "公司名称"]

childMenuCreate(childList)

function childMenuCreate(childList) {
    // 创建二级菜单
    childList.forEach(item => {
        chrome.contextMenus.create({
            id: item,
            title: item,
            contexts: ["selection"],
            parentId: "AppendSelectnContentMneu",
        });
    });
}








//判断是否登录
chrome.contextMenus.onClicked.addListener(async function (info, tabs) {
    // 获取数据
    let MenuId = info.menuItemId
    chrome.storage.local.get('TopeasyAccountCode').then(res => {
        //如果没有 就去登录页面
        if (res.TopeasyAccountCode != null && res.TopeasyAccountCode != "undefined") {
            //直接保存页面
            console.log("已存在 accountcode")
            ContentType(MenuId, tabs)
        } else {
            console.log("不存在 accountcode")
            //登录页面
            CreatePage();
        }
    })

});






//创建页面
function CreatePage() {
    let pagedata = {
        page: "GetLoginPage",
    }
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, pagedata);
    });

}



// 已有accountcode 可直接登录

//判断 
async function ContentType(MenuId, tabs) {

    //获取所有联系方式
    if (MenuId === "ALLContentMenu") {

        let url = tabs.url

        await fetch(url, { method: 'GET' })
            .then(response => response.text())
            .then(res => {

                let ContactInformation = HtmlToData(res)
                //传递数据
                console.log("获取的数据", ContactInformation)

                chrome.tabs.query({ active: true, currentWindow: true }, function (tabsf) {
                    console.log(tabs)
                    chrome.tabs.sendMessage(tabs.id, ContactInformation);
                });

            })
            .catch(err => {
                console.log(err)
            })
    }
    //添加到邮箱
    else {
        console.log(tabs)

        let domainName = "";
        let content = tabs.url.split("://")[1]
        let index = content.indexOf("/")

        if (index != -1) {
            domainName = content.slice(0, index)
        }

        let dataType = ""
        if (MenuId == "Email") {
            dataType = "邮箱"
        } else if (MenuId == "Tel") {
            dataType = "电话"
        } else if (MenuId == "Fax") {
            dataType = "传真"
        } else {
            dataType = MenuId
        }

        let pagedata = {
            page: "AddInfoPage",
            domainName: domainName,
            dataType: dataType,
        }
        chrome.tabs.query({ active: true, currentWindow: true }, function (tab) {
            console.log(pagedata)

            chrome.tabs.sendMessage(tab[0].id, pagedata);
        });
    }

}







//获取的html通过正则获取
function HtmlToData(res) {
    //邮箱
    let Emails = ExtractEmails(res);

    // console.log(Emails)

    //电话
    let Phones = ExtractPhone(res);
    // console.log(Phones)

    //facebook
    let Facebooks = ExtractFaceBook(res)

    // Twitter
    let Twitters = ExtractTwitters(res);
    // console.log(Twitters)

    //Linkedin
    let Linkedins = ExtractLinkedin(res);

    //Skype
    let Skypes = ExtractSkype(res);

    //YouTubes
    let YouTubes = ExtractYoutube(res);
    // console.log(YouTubes)

    // Instagram 
    let Instagrams = ExtractInstagram(res);
    // console.log(Instagrams)

    let Pinterests = ExtractPinterest(res);

    let ContactInformation = {
        page: "GetInfoPage",
        Emails: Emails,
        Phones: Phones,
        Facebooks: Facebooks,
        Instagrams: Instagrams,
        YouTubes: YouTubes,
        Twitters: Twitters,
        Linkedins: Linkedins,
        Skypes: Skypes,
        Pinterests: Pinterests
    }
    return ContactInformation
}





//类型判断
function SelectTypeToNum(selectType) {
    console.log(selectType, "selectType")
    let ContactType;
    if (selectType == "邮箱") {
        ContactType = "0"
    } else if (selectType == "电话") {
        ContactType = "1"
    } else if (selectType == "传真") {
        ContactType = "2"
    } else if (selectType == "地址") {
        ContactType = "3"
    } else if (selectType == "公司名称") {
        ContactType = "4"
    } else if (selectType == "Facebook") {
        ContactType = "5"
    } else if (selectType == "Twitter") {
        ContactType = "6"
    } else if (selectType == "Linkedin") {
        ContactType = "7"
    } else if (selectType == "Skype") {
        ContactType = "8"
    } else if (selectType == "YouTube") {
        ContactType = "9"
    } else if (selectType == "Instagram") {
        ContactType = "10"
    } else if (selectType == "Pinterest") {
        ContactType = "11"
    }
    return ContactType;

}





// 邮箱正则
function ExtractEmails(str) {
    let emailRegex = /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;
    ///[\w_-]+@[\w_-]+(.[\w_-]+){2,}/;
    // /[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)/g;
    // /[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/g;
    let emails = str.match(emailRegex);
    // console.log(emails)
    if (emails != null && emails.length > 0) {
        emails = Duplicate(emails)
    }
    return emails || [];
}

//电话正则
function ExtractPhone(str) {
    let PhoneRegx = /^(\+\d{1,3}[- ]?)?(\d{1,3}[-. ]?){2}\d{4}$/g;
    let phones = str.match(PhoneRegx);

    if (phones != null && phones.length > 0) {
        phones = Duplicate(phones)
    }

    return phones || [];
}


//Facebook 正则
function ExtractFaceBook(str) {
    let faceBookRegex = /https:\/\/www.facebook.com\/\w+/gim;
    let facebooks = str.match(faceBookRegex);
    console.log(facebooks, "facebooks")

    if (facebooks != null && facebooks.length > 0) {
        facebooks = DeleteDuplicate(facebooks)
    }
    return facebooks || [];
}

//Twitter正则   
function ExtractTwitters(str) {
    let twitterRegex = /https:\/\/www.twitter.com\/\w+/gim;
    let twitters = str.match(twitterRegex);

    if (twitters != null && twitters.length > 0) {
        twitters = DeleteDuplicate(twitters)
    }

    return twitters || [];
}

//Linkedin 正则
function ExtractLinkedin(str) {
    let LinkedinRegex = /https:\/\/www.Linkedin.com\/\w+/gim;
    let Linkedins = str.match(LinkedinRegex);

    if (Linkedins != null && Linkedins.length > 0) {
        Linkedins = DeleteDuplicate(Linkedins)
    }

    return Linkedins || [];
}

//skype 正则
function ExtractSkype(str) {
    let SkypeRegex = /https:\/\/www.skype.com\/\w+/gim;
    let Skypes = str.match(SkypeRegex);

    if (Skypes != null && Skypes.length > 0) {
        Skypes = DeleteDuplicate(Skypes)
    }

    return Skypes || [];
}


// Youtube   正则
function ExtractYoutube(str) {
    let YoutubeRegex = /https:\/\/www.youtube.com\/\w+/gim;
    let Youtubes = str.match(YoutubeRegex);

    if (Youtubes != null && Youtubes.length > 0) {
        Youtubes = DeleteDuplicate(Youtubes)
    }

    return Youtubes || [];
}
// Instagram   正则
function ExtractInstagram(str) {
    let InstagramRegex = /https:\/\/www.instagram.com\/\w+/gim;
    let Instagrams = str.match(InstagramRegex);

    if (Instagrams != null && Instagrams.length > 0) {
        Instagrams = DeleteDuplicate(Instagrams)
    }

    return Instagrams || [];
}
//pinterest  正则
function ExtractPinterest(str) {
    let PinterestRegex = /https:\/\/www.pinterest.com\/\w+/gim;
    let Pinterests = str.match(PinterestRegex);

    if (Pinterests != null && Pinterests.length > 0) {
        Pinterests = DeleteDuplicate(Pinterests)
    }
    return Pinterests || []
}

//邮箱正则
function Duplicate(arr) {
    let DataArray = [];
    if (arr.length > 0) {
        arr.forEach(item => {
            if (!item.includes("png") && !item.includes("jpg")) {
                if (!DataArray.includes(item)) {
                    DataArray.push(item)
                }
            }
        });
    }
    return DataArray || []
}

// 去重+去问好
function DeleteDuplicate(arr) {
    let DataArray = [];
    if (arr.length > 0) {
        arr.forEach(item => {
            // item = item.slice(0, item.length - 1)//
            item = item.split("com/")[1]
            if (!DataArray.includes(item)) {
                DataArray.push(item)
            }
        });
    }
    return DataArray || []
}



